﻿// <copyright file="TagsDymanicNodeProvider.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>

namespace CleverCMS.Blog.Services.Infrastructure
{
    using MvcSiteMapProvider;
    using System;
    using System.Linq;
    using System.Collections.Generic;

    using CleverCMS.Core.Infrastructure;
    using CleverCMS.Blog.Services;

    public class BlogEntryTagsDymanicNodeProvider : DynamicNodeProviderBase
    {
        //private BlogEntryService _blogEntryService;
        private BlogEntryService    m_blogService;
        private readonly AppCache   m_appCache;

        public BlogEntryTagsDymanicNodeProvider()
        {
            this.m_appCache = new AppCache();
        }

        public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
        {
            if (m_appCache.Exists("Tags"))
                return (List<DynamicNode>)m_appCache.Get("Tags");

            m_blogService = IoC.Get<BlogEntryService>();
            var nodes = new List<DynamicNode>();

            var tags = m_blogService.GetAllTags().ToList();
            foreach (var tag in tags)
            {
                for (int i = 0; i <= tag.BlogEntries.Count; i++)
                {
                    var tagNode = new DynamicNode { Key = "tag_" + Guid.NewGuid(), Title = tag.Name };
                    tagNode.RouteValues.Add("tag", tag.Name);
                    
                    if (i != 0)
                        tagNode.RouteValues.Add("page", i);
                   
                    tagNode.Action = "Index";
                    tagNode.Controller = "Blog";
                    nodes.Add(tagNode);
                }
            }

            m_appCache.Add("Tags", nodes);
            return nodes;
        }
    }
}
